'use strict';
var HOST = '120.55.114.198';
/**
 * 主要函数功能为完善客户端无法操作完成的复杂逻辑处理和相关缺失功能补充
 * 该文件为Parse服务器云函数功能文件,该文件为main.js使用的辅助函数集合
 * 作者:Jun Xiao
 * 于: 2016年6月1日
 */


/**
 * http请求函数,为Parse云服务使用,封装为短信平台接口请求工具函数
 * @param url
 * @param data
 * @param method
 * @param headers
 * @param callback
 * @constructor
 */
function HTTPRequests(url, data, method, headers, callback) {

    var request_data = '';
    if (typeof data != 'undefined' && typeof data == 'object') {
        request_data = require('querystring').stringify(data);
    }

    var request_method = 'GET';
    if (typeof method != 'undefined' && typeof method == 'string') {
        request_method = method.toUpperCase();
    }

    var request_urlInfo = {};
    if (typeof url != 'undefined' && typeof url == 'object') {
        request_urlInfo['host'] = url.host;
        request_urlInfo['path'] = url['path'];
        request_urlInfo['port'] = url.port;
    }

    if (typeof request_urlInfo.host == 'undefined') {
        request_urlInfo.host = 'http://localhost';
    }

    if (typeof request_urlInfo['path'] == 'undefined') {
        request_urlInfo['path'] = '/';
    }

    if (typeof request_urlInfo.port == 'undefined') {
        request_urlInfo.port = 8080;
    }


    var request_headers = {};
    if (request_method == 'POST') {
        request_headers['Content-Type'] = 'application/json;charset=utf-8';
    } else {
        request_headers['Content-Type'] = 'application/json;charset=utf-8';
    }
    request_headers['Accept'] = 'application/json';

    if (typeof headers != 'undefined' && typeof headers == 'object') {
        for (var key in headers) {
            request_headers[key] = headers[key];
        }
    }

    var request = require('request');
    var options = {
        url: request_urlInfo.host + request_urlInfo['path'],
        headers: request_headers,
        method: "POST"
    };
    request.post({
        url: options.url,
        body: data,
        json: true,
        headers: request_headers
    }, function (err, httpResponse, body) {
        if (!err) {
            if (body) {
                if (body.statusCode == '000000') {
                    callback(null, {code: 200, message: "success"})
                } else {
                    callback('error', {code: 501, message: body.statusMsg})
                }
            }
        } else {
            callback(null, {code: 200, message: "success"});
        }
    });
}

function setCode(mobile, templateId, callback) {

    if (!mobile || !templateId) {
        callback('error1');
    }
    //写入code到redis数据库
    var redis = require('redis');
    var client = redis.createClient({host: HOST, port: 6379, db: 2});
    client.auth("PinYao123");
    client.on("error", function (err) {
        callback(err);
    });
    var sms_code = MathRand();

    var msg_type_code = {
        45930: 'sign', 45940: 'change_mobile', 45937: 'change_password',
        102717: "couponGet", 102720: "mobileAutoSign", 104070: "mobileLogin",137428:"kd_changepass",
        137426:"kd_sign",137828:"kd_mobileLogin"
    };
    client.set(msg_type_code[templateId] + ":" + mobile, sms_code, function (err, replies) {
        if (!err) {
            client.expire(msg_type_code[templateId] + ":" + mobile, 5 * 60, function (err, replies) {
                if (!err) {
                    callback(err, sms_code);
                } else {
                    callback(err);
                }
                client.quit();
            });
        } else {
            callback(err);
            client.quit();
        }
        client.quit();
    });

}

function getCode(mobile, code_type, callBack) {
    //连接redis数据库
    var redis = require('redis');
    var client = redis.createClient({host: HOST, port: 6379, db: 2});
    client.auth("PinYao123");
    client.on("error", function (err) {
        callBack(err);
        client.quit();
    });
    client.get(code_type + ":" + mobile, function (err, replies) {
        callBack(err, replies);
        client.quit();
    });
}

function MathRand() {
    var Num = "";
    for (var i = 0; i < 6; i++) {
        Num += Math.floor(Math.random() * 10);
    }
    return Num;
}

function addUserPoints(user, number, locations, operation, target, oldPoints, callback) {

    var pointsObj = new Parse.Object.extend("PYPoints");
    var points = new pointsObj();

    points.set('user', user);
    points.set('point', number);
    points.set('operation', operation);
    points.set('target', target);
    points.set('targetClassName', locations);
    points.set('oldPoints', oldPoints);
    if (operation == 'comment') {
        points.set('content', '评论加分');
    }
    if (operation == 'firstTenComment') {
        points.set('content', '累计十次评论额外奖励');
    }
    if (operation == 'firstHundredComment') {
        points.set('content', '累计百次评论额外奖励');
    }
    if (operation == 'answerAdopt') {
        points.set('content', "问答悬赏获得");
    }
    if (operation == 'FirstMobileSign') {
        points.set('content', "手机快速注册");
    }
    if(operation == 'OauthSign_wx'){
        points.set('content',"第三方微信注册");
    }
    if(operation == 'mobileSign'){
        points.set('content',"手机注册");
    }

    Parse.Cloud.useMasterKey();
    points.save(null, {
        success: function (msg) {
            user.increment('point', number);
            user.save(null, {
                success: function (user_obj) {
                    callback(true);
                }, error: function (err,error) {
                    console.log(err,error);
                    callback(false)
                }
            });
        }, error: function (err) {
            console.log(err);
            callback(false)
        }
    });
}

/**
 * 创建店铺活动
 * @param pharmacies
 * @param name
 * @param content
 * @param isTop
 * @param beginDate
 * @param endDate
 * @param url
 * @param images
 */
function createPharmacyActivity(pharmacies, name, content, isTop, beginDate, endDate, url, images, isStrId) {
    if (pharmacies.length == 0) {
        res.error("管理店铺数量为0");
    }
    for (var i = 0; i < pharmacies.length; i++) {
        var PharmacyActivity = new Parse.Object.extend("PYPharmacyActivity");
        var objTemp = new PharmacyActivity();
        objTemp.set('name', name);
        objTemp.set('content', content);
        if (isTop) {
            objTemp.set('isTop', isTop);
        }

        if (!beginDate) {
            beginDate = new Date();
        } else {
            beginDate = new Date(beginDate);
        }
        objTemp.set("beginDate", beginDate);
        if (endDate) {
            objTemp.set("endDate", new Date(endDate));
        }

        if (url) {
            objTemp.set("url", url);
        } else {
            objTemp.set("url", "");
        }

        if (images) {
            if (images.length > 0) {
                objTemp.set("images", images);
            } else {
                objTemp.set("images", []);
            }
        } else {
            objTemp.set("images", []);
        }
        if (isStrId) {
            objTemp.set("pharmacy", Parse.Object.extend("PYPharmacy").createWithoutData(pharmacies[i]))
        } else {
            objTemp.set("pharmacy", pharmacies[i]);
        }
        objTemp.save().then(function (msg) {
        }, function (err) {
        });
    }
}

function getAmpAroundList(location, page, callback) {
    var requestUrl = 'http://restapi.amap.com/v3/place/around';
    Parse.Cloud.httpRequest({
        method: 'GET',
        params: {
            key: "eef84aa720ff5fd55283589fe77faa5e",
            keywords: "药店|药房",
            types: "090601",
            offset: 20,
            page: page,
            radius: 3000,
            location: location
        },
        headers: {
            'Content-Type': 'application/json;charset=utf-8',
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 ' +
            '(KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'
        },
        url: requestUrl
    }).then(function (httpResponse) {
        callback(JSON.parse(httpResponse.text));
    }, function (httpResponse) {
        callback(false);
    });
}


function getRad(d) {
    var PI = Math.PI;
    return d * PI / 180.0;
}

/**
 * approx distance between two points on earth ellipsoid
 * @param {Object} lat1
 * @param {Object} lng1
 * @param {Object} lat2
 * @param {Object} lng2
 */
function getFlatternDistance(lat1, lng1, lat2, lng2) {
    lat1 = parseFloat(lat1);
    lat2 = parseFloat(lat2);
    lng1 = parseFloat(lng1);
    lng2 = parseFloat(lng2);

    var EARTH_RADIUS = 6378137.0;    //单位M


    var f = getRad((lat1 + lat2) / 2);
    var g = getRad((lat1 - lat2) / 2);
    var l = getRad((lng1 - lng2) / 2);

    var sg = Math.sin(g);
    var sl = Math.sin(l);
    var sf = Math.sin(f);

    var s, c, w, r, d, h1, h2;
    var a = EARTH_RADIUS;
    var fl = 1 / 298.257;

    sg = sg * sg;
    sl = sl * sl;
    sf = sf * sf;

    s = sg * (1 - sl) + (1 - sf) * sl;
    c = (1 - sg) * (1 - sl) + sf * sl;

    w = Math.atan(Math.sqrt(s / c));
    r = Math.sqrt(s * c) / w;
    d = 2 * w * a;
    h1 = (3 * r - 1) / 2 / c;
    h2 = (3 * r + 1) / 2 / s;

    var distance = d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg));
    if (distance < 1000) {
        distance = String(distance) + 'm';
    } else {
        distance = String((distance / 1000).toFixed(1)) + 'km';
    }

    return distance;
}

function getPharmacyActivities(p, temp, callBack) {

    var Activity = new Parse.Query("PYPharmacyActivity");
    Activity.equalTo('pharmacy', p);
    Activity.lessThan('beginDate', new Date());
    Activity.greaterThan('endDate', new Date());
    Activity.descending('isTop');
    Activity.ascending('created_at');
    Activity.first().then(function (activity) {
        if (activity) {
            temp.activityInfo = activity.get('name') + ',' + activity.get('content');
        } else {
            temp.activityInfo = '';
        }
        callBack(null, temp);
    }, function (err) {
        console.log(err);
    });
}

function getPharmacyCoupon(p, temp, callback) {
    var CouponTemplate = new Parse.Query("PYCouponTemplate");
    CouponTemplate.containedIn('pharmacies', [p]);
    CouponTemplate.lessThan('validityBegin', new Date());
    CouponTemplate.greaterThan('validityEnd', new Date());
    CouponTemplate.descending('worth');
    CouponTemplate.ascending('created_at');
    CouponTemplate.first().then(function (coupon) {
        if (coupon.get('isNoMore')) {
            temp.hasCoupon = true;
        } else {
            temp.hasCoupon = false;
        }
        console.log(temp);
        callback(null, temp);
    }, function (err) {
        console.log(err);
    });
}

function getPharmacyDrugSaleCount(p, temp, drug, callback) {
    //先获取所有的优惠药品的数量
    Parse.Cloud.useMasterKey();
    var pharmacyDrug = new Parse.Query("PYPharmacyDrug");
    pharmacyDrug.equalTo('pharmacy', p);
    pharmacyDrug.equalTo('isSale', true);
    pharmacyDrug.count().then(function (count) {
        if (count) {
            temp.saleDrugCount = count;
            //如果还有drug传入,则还要寻找是否有该药品正在优惠
            if (drug) {
                pharmacyDrug.equalTo('drug', Parse.Object.extend("PYDrug").createWithoutData(drug));
                pharmacyDrug.first().then(function (drugInfo) {
                    if (drugInfo) {
                        temp.drugOnSale = true;
                        temp.saleDrugInfo = {
                            drugName: drugInfo.get("name"),
                            drugHasSoldPrice: drugInfo.get("price") - drugInfo.get("salePrice")
                        };
                        callback(null, temp);
                    } else {
                        //查看是否在售该药
                        var _pharmacyDrug1 = new Parse.Query("PYPharmacyDrug");
                        _pharmacyDrug1.equalTo('pharmacy', p);
                        _pharmacyDrug1.equalTo('drug', Parse.Object.extend("PYDrug").createWithoutData(drug));
                        _pharmacyDrug1.first().then(function (drugSale) {
                            if (drugSale) {
                                temp.drugOnSale = true;
                            } else {
                                temp.drugOnSale = false;
                            }
                            callback(null, temp);
                        });
                    }
                })
            } else {

                temp.drugOnSale = false;
                callback(null, temp);
            }

        } else {
            temp.saleDrugCount = 0;
            //查看是否在售该药
            if (drug) {
                var _pharmacyDrug2 = new Parse.Query("PYPharmacyDrug");
                _pharmacyDrug2.equalTo('pharmacy', p);
                _pharmacyDrug2.equalTo('drug', Parse.Object.extend("PYDrug").createWithoutData(drug));
                _pharmacyDrug2.first().then(function (drugSale) {
                    if (drugSale) {
                        temp.drugOnSale = true;
                    } else {
                        temp.drugOnSale = false;
                    }
                    callback(null, temp);
                });
            }
            setTimeout(callback(null, temp), 2000)
        }
    }, function (err) {
        console.log('error:');
    });
}

function compareAMPAndLocal(local, amp, res, callback) {
    var AMPharmacies = amp.pois;
    var results = [];
    for (var m = 0; m < AMPharmacies.length; m++) {
        if (!isInArray(AMPharmacies[m].id, local)) {
            var temp = {};
            temp.pharmacyId = '';
            temp.name = AMPharmacies[m].name;
            if (typeof AMPharmacies[m].tel == 'string') {
                temp.tel = AMPharmacies[m].tel.split(";");
            } else {
                temp.tel = AMPharmacies[m].tel;
            }
            temp.address = AMPharmacies[m].address;
            temp.distance = AMPharmacies[m].distance;
            temp.location = CreateGEOObject(AMPharmacies[m].location);
            temp.mapId = AMPharmacies[m].id;
            local.push(temp);
        }
    }
    callback(local, res);
}

function CreateGEOObject(location) {
    var xL = location.split(',')[0];
    var yL = location.split(',')[1];
    return new Parse.GeoPoint({latitude: parseFloat(yL), longitude: parseFloat(xL)});
}

function isInArray(id, local) {
    var res = false;
    for (var i = 0; i < local.length; i++) {
        if (id == local[i].mapId) {
            res = true;
            break;
        }
    }
    return res;
}

function sendPushToSingleUser(type, fromUser, toUser, target) {
    //首先根据接受推送用户查询channelId
    Parse.Cloud.useMasterKey();
    var _User = new Parse.Query("_User");
    _User.get(toUser.id).then(function (toUserObj) {
        if (toUserObj) {
            var installation = toUserObj.get("installation");
            if (installation) {
                var data = {
                    "_ApplicationId": "myAppId",
                    "_ClientVersion": "js1.6.14",
                    "_MasterKey": "masterKey",
                    "_InstallationId": "71d7fb3d-b5fc-62de-d1f1-45e2be105917"
                };
                data.where = {
                    "objectId": installation.id,
                    "deviceType": {"$in": [toUserObj.get("deviceType").toLowerCase()]}
                };
                data.data = {};
                switch (type) {
                    case 'drugComment':
                        data.data.alert = "药品评论有回复啦!点击查看吧~";
                        data.data.relatedId = target;
                        data.data.relatedCollection = "PYDrugComment";
                        break;
                    case 'feedComment':
                        data.data.alert = "帖子有回复啦!点击查看吧~";
                        data.data.relatedId = target;
                        data.data.relatedCollection = "PYFeedComment";
                        break;
                    case 'questionAnswer':
                        data.data.alert = "提问有最新回复啦!点击查看吧~";
                        data.data.relatedId = target;
                        data.data.relatedCollection = "PYQuestion";
                        break;
                    case 'answerAdopt':
                        data.data.alert = "您的回答被采纳啦!点击查看吧~";
                        data.data.relatedId = target;
                        data.data.relatedCollection = "PYQuestion";
                        break;
                    default :
                        data.data.alert = "有新消息!点击查看吧~";
                        data.data.relatedId = target;
                        data.data.relatedCollection = "PYNewMessage";
                        break;
                }
                if (toUserObj.get("deviceType").toLowerCase() == 'ios') {
                    data.data.badge = "Increment";
                }
                Parse.Cloud.httpRequest({
                    method: 'POST',
                    body: data,
                    headers: {
                        'Content-Type': 'application/json;charset=utf-8',
                        'X-Parse-Application-Id': 'myAppId',
                        'X-Parse-Master-Key': 'masterKey'
                    },
                    url: 'http://127.0.0.1:1337/parse/push'
                }).then(function (httpResponse) {
                    callback(JSON.parse(httpResponse.text));
                }, function (httpResponse) {
                    callback(false);
                });
            }
        }
    })
}


function sendPushToUsers(type, fromUser, toUsers, target) {
    console.log("开发中");
}

function getPassCode(len) {
    len = len || 32;
    var $chars = '123456780';
    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length;
    var pwd = '';
    for (var i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

module.exports = {
    HTTPRequests: HTTPRequests,
    setCode: setCode,
    getCode: getCode,
    addUserPoints: addUserPoints,
    createPharmacyActivity: createPharmacyActivity,
    getAmpAroundList: getAmpAroundList,
    getFlatternDistance: getFlatternDistance,
    getPharmacyActivities: getPharmacyActivities,
    getPharmacyCoupon: getPharmacyCoupon,
    getPharmacyDrugSaleCount: getPharmacyDrugSaleCount,
    compareAMPAndLocal: compareAMPAndLocal,
    sendPushToSingleUser: sendPushToSingleUser,
    sendPushToUsers: sendPushToUsers,
    getPassCode: getPassCode,
    MathRand: MathRand
};
